﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Xml.Serialization;
using Torrenter.Common.Helpers;

namespace Torrenter.Common.Objects
{
    [Serializable]
    public class TorrentRepository
    {
        #region properties

        public const string FILENAME = "Torrents.xml";

        [XmlIgnore]
        public static string FileName
        {
            get { return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, FILENAME); }
        }

        public ObservableCollection<Show> Shows { get; set; }

        public DateTime LastUpdate { get; set; }

        #endregion // properties

        #region Save and load

        public static TorrentRepository GetTorrents()
        {
            try
            {
                return (TorrentRepository)XmlSerializerHelper.FromXmlFile(FileName, typeof(TorrentRepository));
            }
            catch (Exception)
            {
                try
                {
                    var t = new TorrentRepository {Shows = new ObservableCollection<Show>()};
                    XmlSerializerHelper.ToFile(t, typeof(TorrentRepository), FileName);
                    return t;
                }
                catch (Exception ex)
                {

                    throw;
                }

            }
        }

        public void SaveTorrents()
        {
            SaveTorrents(this);
        }


        private static void SaveTorrents(TorrentRepository tr)
        {
            XmlSerializerHelper.ToFile(tr, FileName);
        }


        #endregion // Save and load

        #region add and remove methods

        public void AddNewShow(Show show)
        {
            Shows.Add(show);
            SaveTorrents();
        }

        public void AddSeason(ShowSeason showSeason)
        {
            var show = Shows.FirstOrDefault(s => s.ShowName == showSeason.ShowName);
            if (show == null)
            {
                show = new Show() { ShowName = showSeason.ShowName };
                Shows.Add(show);
            }
            show.AddSeason(showSeason);
            
            SaveTorrents();
        }

        public void RemoveShow(Show show)
        {            
            Shows.Remove(show);
            SaveTorrents();
        }
            
            

        #endregion // add and remove methods

        
    }
  
}
